/*
 * Title: WADS
 * Description: Web-based Auto flow Documents System
 * Copyright: 2007
 * Company: CoE
 * @author: Mr.Nattasan Wang-Aphisit
 * @version 1.1
 */

package wads.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import wads.com.AutoDocumentTransaction;
import wads.com.DocumentTemplateInfo;
import wads.com.UserInfo;
import wads.com.WADTools;

public class SearchAndShowUnsuccessRestrictDoc extends HttpServlet {
  private static final long serialVersionUID = 97559154726845617L;
  
  private static final String CONTENT_TYPE = WADTools.SERVLET_CONTENT_TYPE;
  /**Initialize global variables*/
  String RestrictNameFromLogin;
  Vector AllPowerUser = new Vector();
  ServletOutputStream sos;
  public final int USER = 1;
  public final int FULLUSER = 2;
  public final int EMAIL = 5;
  String app_Path;
  Vector allPowerUser;
  Vector documentIDFile;
  AutoDocumentTransaction adTran;
  DocumentTemplateInfo dtInfo;
  String template_ID;
  String template_Name;
  String ownerName;
  String currentUser;
  String sendDate;
  String updateDate;
  UserInfo uiRestrictUser;
  String fullNameRestrict;
  UserInfo uiPowerUser;
  String fullNamePower;
  String powerName;
  String createdTime;
  String submitTime;
  String temp;
  HttpSession session;
  int LIMITUP_GREEN;
  int LIMITDOWN_YELLOW;
  int LIMITUP_YELLOW;
  int LIMITDOWN_RED;
  Properties prop = new Properties();
  String color;
  int percent;
  String image;
  String emailPowerUser;
  Calendar cal_ct, cal_st;

  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }
  /**Process the HTTP Get request*/
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);

    session = request.getSession(false);
    RestrictNameFromLogin = (String)session.getAttribute("UserName");
    //app_Path = this.getInitParameter("app_Path");
    app_Path = WADTools.APP_PATH;
    sos = response.getOutputStream();
    prop.load(new FileInputStream(app_Path+"res/day.properties"));
    LIMITUP_GREEN    = Integer.parseInt(prop.getProperty("LIMITUP_GREEN"));
    LIMITDOWN_YELLOW = Integer.parseInt(prop.getProperty("LIMITDOWN_YELLOW"));
    LIMITUP_YELLOW   = Integer.parseInt(prop.getProperty("LIMITUP_YELLOW"));
    LIMITDOWN_RED    = Integer.parseInt(prop.getProperty("LIMITDOWN_RED"));
    this.readBeginninghtml();

    //find Restrictname form login how????

   //RestrictNameFromLogin = "restrict2";
   //String RestrictNameFromLogin  = "";
   //try { RestrictNameFromLogin  = request.getParameter("UserName"); } catch (Exception e) { e.printStackTrace(); }

    fullNameRestrict = getFullNameofRestrictedUser(RestrictNameFromLogin);
    //choose user to show
    if(fullNameRestrict != null){
      AllPowerUser = this.findAllPowerUser();
      //filter restrict document in each power User by RestrictNameLogin
      this.fillandShowRestrictDocument(AllPowerUser, fullNameRestrict);
    }
    else{
     sos.println("Not Found Restrict Document In Progress");
    }
    sos.close();
  }
  
  /**Clean up resources*/
  public void destroy() {
  }
  
  public Vector findAllPowerUser(){
    Vector<String> allPowerUser = new Vector<String>();
    File doc_Path = new File(app_Path+"res/docs/InProgressAutoDoc/");
    if(doc_Path.isDirectory()){
      File[] listUserPath = doc_Path.listFiles();
      for(int i=0; i<listUserPath.length ;i++)
        allPowerUser.add(listUserPath[i].getName());
    }

    return allPowerUser;
  }

  public Vector getDocumentInUser(String user){
    Vector<String> documentIDFile = new Vector<String>();
    File user_Path = new File(app_Path+"res/docs/InProgressAutoDoc/" + user);
    File[] listDocument = user_Path.listFiles();
    for(int i=0; i< listDocument.length; i++)
      documentIDFile.add(listDocument[i].getName());

    return documentIDFile;
  }
  public void readBeginninghtml() {
    File htmlFile = new File("restrictedusersection.html");
    String temp = null;
    byte[] buf = new byte[1024];
    boolean check = true;
    try{
        BufferedReader br = new BufferedReader(new FileReader(htmlFile));
        while((temp = br.readLine()) != null){
          if((temp.indexOf("hiddenField") == -1) && check){
         // sos.println(temp);
            buf = temp.getBytes();
            sos.write(buf,0,temp.length());
          }
          else{
            check = false;
          }
            //this.fillDataAll();
        }
        br.close();
      }catch(Exception e){
        System.out.println("Exception thrown from SearchAndShowUnsuccessRestrictedDoc.readBeginninghtml()");
        e.printStackTrace();
      }
  }
  public String getFullNameofRestrictedUser(String name){
    String restrictUserFile = app_Path+"res/user/RestrictUser/RestrictUser.org";

    //Read Object of RestrictUser
    try{
      ObjectInputStream ois = new ObjectInputStream(new FileInputStream(restrictUserFile));
      uiRestrictUser = (UserInfo)ois.readObject();
      ois.close();
    }catch(Exception e) {
      System.out.println("Exception thrown from SearchAndShowUnsuccessRestrictedDoc.getFullNameofRestrictedUser()");
      e.printStackTrace();
    }

    if(!uiRestrictUser.isEmpty()){
      for(int i=0; i<uiRestrictUser.getSize(); i++){
        if(name.equals(uiRestrictUser.getUserDataAt(i).getUsername()))
          fullNameRestrict = uiRestrictUser.getUserDataAt(i).getName();
      }
    }
    else
      return null;

    return fullNameRestrict;
  }

  public String getFullNameofPowerUser(String name){
    String powerUserFile= null;
    String orgName = null;
    Properties prop = new Properties();

    try{
      //Load OrgName of PowerUser
      prop.load(new FileInputStream(app_Path+"res/wad_app.properties"));
      orgName = prop.getProperty("orgName","No");
      powerUserFile = app_Path+"res/user/PowerUser/" + orgName;

      //Read Object of RestrictUser
      ObjectInputStream ois = new ObjectInputStream(new FileInputStream(powerUserFile));
      uiPowerUser = (UserInfo)ois.readObject();
      ois.close();
    }catch(Exception e) {
      System.out.println("Exception thrown from SearchAndShowUnsuccessRestrictedDoc.getFullNameofPowerUser()");
      e.printStackTrace();
    }

    if(!uiPowerUser.isEmpty()){
       for(int i=0; i<uiPowerUser.getSize(); i++){
          if(name.equals(uiPowerUser.getUserDataAt(i).getUsername())){
            fullNamePower = uiPowerUser.getUserDataAt(i).getName();
            emailPowerUser = uiPowerUser.getUserDataAt(i).getEMail();
          }
       }
    }
    return fullNamePower;
  }

  public String getCreatedTime(Date createdTime){
    cal_ct.setTime(createdTime);
    int date = cal_ct.get(Calendar.DAY_OF_MONTH);
    int month = cal_ct.get(Calendar.MONTH);
    int year = cal_ct.get(Calendar.YEAR)-57;

    return date + "/" + month + "/" + year;
  }

  public String getSubmitTime(Date submitTime){
    cal_st.setTime(submitTime);
    int date = cal_st.get(Calendar.DAY_OF_MONTH);
    int month = cal_st.get(Calendar.MONTH);
    int year = cal_st.get(Calendar.YEAR)-57;

    return date + "/" + month + "/" + year;
  }

  public String getProgressBarColor(Date createdTime, Date submitTime){
    String color = null;
    cal_ct.setTime(createdTime);
    cal_st.setTime(submitTime);
    int ctDate  = cal_ct.get(Calendar.DAY_OF_MONTH);
    int ctMonth = cal_ct.get(Calendar.MONTH);
    int ctYear  = cal_ct.get(Calendar.YEAR)-57;
    int stDate  = cal_st.get(Calendar.DAY_OF_MONTH);
    int stMonth = cal_st.get(Calendar.MONTH);
    int stYear  = cal_st.get(Calendar.YEAR)-57;
    int check = 0;
    int def = 0;
    if(createdTime.equals(submitTime)){
      return "green";
    }else{
      if((def = (stYear - ctYear)) > 0)
        check = check + (def * 365);

      if((def = (stMonth - ctMonth)) > 0)
        check = check + (def * 30);

      if((def = (stDate - ctDate)) > 0)
        check = check + def;
      ///check limit

    }
    if(check >= 0 && check <= LIMITUP_GREEN)
      color = "green";
    else if(check >= LIMITDOWN_YELLOW && check <= LIMITUP_YELLOW)
      color = "yellow";
    else if(check >= LIMITDOWN_RED)
      color = "red";

    return color;
  }
  public int getProgressBarPercent(String currentUser){
    int numberUser = 0;
    int indexCurrentUser = 0;
    int percent = 0;
    String user = null;
    String temp = "0";

    try{
      ObjectInputStream oisa = new ObjectInputStream(new FileInputStream(app_Path+"res/docs/activeDocTemplate/"+template_ID+"/docTemplate.info"));
      dtInfo = (DocumentTemplateInfo)oisa.readObject();
    }catch(Exception e) {
      System.out.println("Exception thrown from SearchAndShowUnsuccessRestrictedDoc.getProgressBarPercent()");
      e.printStackTrace();
    }
    
    if(!dtInfo.getFlow_Users().isEmpty()){
      int i=1;

      user = dtInfo.getFirstUser();
      if(currentUser.equals(user))
        indexCurrentUser = i-1;

      while((user = dtInfo.whois_nextUser_from_thisUser(user)) != null){
        i++;
        if(currentUser.equals(user))
          indexCurrentUser = i-1;
        numberUser = i;
      }
    }
    if((indexCurrentUser != 0) && (numberUser != 0)){
      percent = (int)((indexCurrentUser*100)/numberUser);
      temp = String.valueOf(percent);
      temp = temp.substring(0,temp.length()-1);
      temp = temp + "0";
    }
    return Integer.parseInt(temp);
  }

  public void fillandShowRestrictDocument(Vector PowerUser, String RestrictName){
     //String user = "power1";
     String user = null;
     //boolean setTitle = false;
     //boolean  hasRestrictDocument = false;
     String BGColor;
     int h=0;
     for(int j=0; j< PowerUser.size(); j++){
      //hasRestrictDocument = true;
       user = PowerUser.elementAt(j).toString();
       documentIDFile = this.getDocumentInUser(user);
       for(int i=0; i<documentIDFile.size(); i++){
         if(h%2 != 0)
           BGColor = "#F0F0F0";
         else
           BGColor = "#CCCCCC";
         
         h++;
         try{
           ObjectInputStream ois = new ObjectInputStream(new FileInputStream(app_Path+"res/docs/InProgressAutoDoc/"+user+"/"+documentIDFile.elementAt(i)));
           adTran = (AutoDocumentTransaction)ois.readObject();
           template_ID = adTran.getTemplate_ID();
           template_Name = adTran.getTemplate_Name();

           //get ownerName    FullName of User
           ownerName = this.getFullNameofRestrictedUser(adTran.getOwner_Name());
           if(ownerName.equals(RestrictName)){
             //get powerUserName   FullName of PowerUser
             powerName = this.getFullNameofPowerUser(user);
             //get createdTime
             createdTime = this.getCreatedTime(adTran.getCreated_Date());
             //get submitTime after
             submitTime = this.getSubmitTime(Calendar.getInstance().getTime());
             //if(adTran.getSubmitDate() != null)
             //  submitTime = this.getSubmitTime(adTran.getSubmitDate().getTime());
             //else
             //  submitTime = createdTime;

             //get percent to manage document
             percent = this.getProgressBarPercent(user);
             //get color to show time of document
             Date stDate = Calendar.getInstance().getTime();
             if(adTran.getSubmitDate() != null)
               color = this.getProgressBarColor(adTran.getCreated_Date(),stDate);
             else{
               color = this.getProgressBarColor(adTran.getCreated_Date(),stDate);
             }
             //combine String image to show
             image = "../images/" + color + "_" + percent + ".gif";
             System.out.println(image);

             sendDate = adTran.getCreated_Date().toString();
             updateDate = adTran.getCurrentTime().toString();
             //updateDate = Calendar.getInstance().

             ObjectInputStream oisa = new ObjectInputStream(new FileInputStream(app_Path+"res/docs/activeDocTemplate/"+template_ID+"/docTemplate.info"));
             dtInfo = (DocumentTemplateInfo)oisa.readObject();
             String templateName = dtInfo.getTemplate_Name();
             //add code to show document
             templateName = "<a href=servlet/show?ID=" + adTran.getTransaction_ID() + "&user=" + user + ">" + templateName + "</a>";

             temp = " <tr bgcolor="+ BGColor +"><td width=60>" + template_ID +
               "</td><td width=200>" + templateName +
               "</td><td width=200>" + ownerName +
               "</td><td width=50>" + createdTime +
               "</td><td width=200>" + "<a href=mailto:" + emailPowerUser + ">" + fullNamePower + "</a>" +
               "</td><td width=50>" + submitTime +
               "</td><td width=200><img src=" + "\"" + image + "\"" + " width=200 height=12></tr>";

             sos.write(temp.getBytes(),0,temp.length());
             ois.close();
           }
         }catch(Exception e) {
           System.out.println("Exception thrown from SearchAndShowUnsuccessRestrictedDoc.fillandShowRestrictDocument()");
           e.printStackTrace();
         }

     }
    }


  }
}